<?php

declare(strict_types=1);

namespace LnkAdmin\service;

use LnkAdmin\model\auth\AdminModel;
use LnkAdmin\model\auth\AdminRoleModel;
use LnkAdmin\model\auth\Permission;
use lite\controller\traits\Crud;
use lite\exception\LiteException;
use LnkAdmin\model\auth\RolePermissionModel;
use think\facade\Db;

class MenuService
{



    public static function getMenu($where = [])
    {
        $menu = [];
        $menu =  Permission::where($where)->order('weigh desc')->select();
        foreach ($menu as &$v) {
            $v['path'] = 1;
        }
        return $menu;
    }

    public static function getUserMenu($where = [])
    {
        $menu = [];
        $menu =  Permission::where($where)->order('weigh desc')->select();
        foreach ($menu as &$v) {
            $v['path'] = 1;
        }
        return $menu;
    }

    public static function getMenuTree()
    {

        $menu =  self::getMenu();
        $treeMenu = self::buildMenuTree($menu);
        return $treeMenu;
    }



    public static function buildMenuTree($menuItems, $parentId = null, $keyName = 'permission_mark', $parentKeyName = 'parent_mark')
    {
        $tree = [];
        foreach ($menuItems as $k => $menuItem) {
            if ($menuItem[$parentKeyName] == $parentId) {

                $menuItem['children']  = self::buildMenuTree($menuItems, $menuItem[$keyName]);
                //   var_dump($menuItem);
                $tree[] = $menuItem;
            }
        }
        return $tree;
    }

    public static function buildMenuList($menuTree, $parent_mark = null)
    {
        $list = [];
        foreach ($menuTree as $k => $v) {
            $v['parent_mark'] = $parent_mark;
            $arrTmp = $v;
            unset($arrTmp['children']);
            $list[] = $arrTmp;
            if (isset($v['children']) && count($v['children']) > 0) {

                $arrTmp = self::buildMenuList($v['children'], $v['permission_mark']);
                $list = array_merge($list, $arrTmp);
            }
        }
        return $list;
    }


    // 获取后台用户菜单
    public static function userMenu($adminId, $menu = [])
    {
        $admin = AdminModel::where('id', $adminId)->find();
        $roleIds = AdminRoleModel::where('admin_id', $admin->id)->column('role_id');
        $rules = RolePermissionModel::whereIn('role_id',$roleIds)->column('rule');
        $where = [
            // ['type', '<>', 2],

        ];
        if ($admin->is_super != 1) {
            array_push($where, ['permission_mark', 'in', $rules]);
        }
        $menu =  self::getUserMenu($where);
        $treeMenu = self::buildMenuTree($menu);
        return $treeMenu;
    }

    function removeKey($key, &$array, $childKey = 'children')
    {
        if (isset($array[$key])) {
            unset($array[$key]);
            return;
        }
        foreach ($array as &$item)
            if (isset($item[$childKey]))
                $this->removeKey($key, $item[$childKey], $childKey);
    }
}
